<?php
/**
 * $Id: JXwebAuto.php 1 2009-07-30 10:06:11Z hainam $
**/
require_once 'JXwebAPI.php';

class JXwebAuto extends JXwebAPI {
  
  function searchNPCByLevel($Level, $exact = false) {
    $result = ajax_GetMapUnitInfo($this->CityID, JXW_MAP_WORLD, $this->CityPos);
    $MapUnitInfo = Tools::decode($result->data);
    if (! is_array($MapUnitInfo)) {
      addLog('Khong thay tim NPC');
      die;
    }
    
    $weight = $exact ? 1000 : 200;
    $NPCPos = 0;
    $minScore = 10000;
    
    foreach ($MapUnitInfo as $Unit) {
      if ($Unit->Type != 5) {
        $score = Tools::TravelTime($this, $Unit->Pos);
        if ($Unit->Level != $Level) {
          // danh vuot cap nguy hiem hon danh duoi cap!
          $score += $weight*abs($Level-$Unit->Pos)*($Unit->Level>$Level ? 1.5 : 1);
        }
        if ($score < $minScore) {
          $NPCPos = $Unit->Pos;
          $minScore = $score;
        }
      }
    }
    return $NPCPos;
  }

  /**
   * Read event info and process.
   * Ref: JS function HtmlEvent(i)
   */
  function processEvent() {
    $result = ajax_GetValidEvent($this->CityID);
    //addLog($result->data);
    $data = Tools::decode($result->data);
    //addLog(var_export($data, true));

    $nextTime = self::$checkTime;
    $now = time();
    $flag = array(
                  'thuthap' => true,
                  'xuattran' => true,
                  'hoitham' => true,
                  'nhiemvu' => true,
                  'bophong' => false,   // xay lai he thong phong thu
                  'repeat' => false,    //if there are new-born event and we need to proceed right now
                  'capnhat' => false,
                  );
    $buildingsBusy = array();
    $herosLeave = array();
    
    foreach ($data as $event) {
      if ($event->EventType == 0) continue; // empty list: no active event
      //
      //addLog(sprintf('Event time %d, act %d, type %d, target %d',
      //               $event->RemainTime,
      //               $event->ActionType,
      //               $event->EventType,
      //               $event->TargetCity
      //               ));

      // Xu li event het han
      if ($event->RemainTime <= 0){
        if ($event->ActionType != JXW_ACTION_THUTHAP) $flag['capnhat'] = true;
        $result1 = ajax_ProcessOverdueEvent($this->CityID, $event->ID);
        addDebug($result1);
      }
      else {
        $nextTime = min($nextTime, $event->RemainTime);
      }

      // Xu li cac event
      if ($event->ActionType == JXW_ACTION_CONGKICH && $event->TargetCity == $this->CityPos) {
        if (!in_array($event->ID, $this->config['Actions']['event'])) {
          if ($event->FromCityName != $this->config['options']['owner']) {
            $this->config['Actions']['event'][] = $event->ID;
            $this->alert(sprintf("Ban se bi %s tan cong trong %d phut nua\n(bat dau luc %s, ket thuc luc %s)", $event->FromCityName, round($event->RemainTime/60), $event->BeginTime, $event->OverTime));
          }
          else {
            // thao bo HK
            $this->config['Actions']['event'][] = $event->ID;
            $this->config['Actions']['op']['bophong'] = $now - 1;
            $this->bophong(false);
            $this->config['Actions']['op']['bophong'] = $now + $event->RemainTime + 1;
          }
        }
        
        if ($event->RemainTime <= 0) $flag['bophong'] = true;
      }
      
      if ($event->ActionType == JXW_ACTION_THUTHAP) {
        $flag['thuthap'] = $event->RemainTime <= 0;
      }
      
      if ($event->ActionType == JXW_ACTION_THUTHAPNHIEMVU || $event->ActionType == JXW_ACTION_TIMTHOREN) {
        $flag['nhiemvu'] = $event->RemainTime <= 0;
      }
      
      if ($event->ActionType == JXW_ACTION_TROVE) {
        $flag['xuattran'] = $event->RemainTime <= 0;
        
        if ($this->config['options']['op_thn'] && $event->RemainTime > $this->config['options']['op_thn_time']*60) {
          // trieu hoi nhanh
          ajax_AddCorpsEvent($this->CityID, JXW_ACTION_TRIEUHOINHANH, JXW_UNIT_CITY, 0, $this->CityPos);
          $flag['repeat'] = true;
        }
      }
      
      if (
          ($event->ActionType == JXW_ACTION_DOTHAM) ||  //do tham mat dao 
          ($event->ActionType == JXW_ACTION_CONGKICH && $event->EventType == 4 && $event->TargetCity != $this->CityPos)  // hoac cong kich
      ) {
        // se con cap nhat lai khi tro ve
        $flag['xuattran'] = false;
        //addLog($event->RemainTime . ' con lai, them ' . Tools::TravelTime($this, $event->TargetCity));
      }
      
      if ($event->ActionType == JXW_ACTION_HERO_LEAVE) {// HK dang roi khoi
        $herosLeave[] = $event->EventPos; //EventPos = Junta
        addLog('HK '. $this->template['Junta'][$event->EventPos] .' sẽ rời khỏi trong '. $event->RemainTime .' giây');
      }
      
      if ($event->ActionType == JXW_ACTION_HERO_ASK && $event->EventType == 1) {
        $flag['hoitham'] = false;
        if ($event->RemainTime <= 0 && $this->config['options']['op_hoitham']) $flag['repeat'] = true;
      }
      
      if ($event->ActionType == JXW_ACTION_XAY) {
        $this->config['Actions']['op']['bophong'] = $now + min($this->config['Actions']['op']['bophong'], $even->RemainTime);
      }
      
      if (in_array($event->ActionType, array(1,2,3,4,5,6,8,27,29,30)) && $event->EventType == 1) {
        $buildingsBusy[] = $event->EventPos;
      }
    }
    //addLog(implode(' ', $buildingsBusy));
    
    $this->user['next'] = $now + $nextTime;

    if ($flag['capnhat']) $this->needUpdate['UserInfo'] = true;

    if ($flag['thuthap'] && $this->config['options']['op_thuthap']) {
      $this->thuthap();
    }
    
    if ($flag['nhiemvu'] && $this->config['options']['op_nhiemvu']) {
      $this->nhiemvu();
    }
    
    if ($flag['xuattran'] && $this->config['options']['op_xuattran']) {
      $this->xuattran();
    }
    
    if ($this->config['options']['op_hoitham']) {
      foreach ($this->config['Buildings'] as $b) {
        $Junta = $b['Index'] - 11;
        if (! in_array($b['Pos'], $buildingsBusy)   // nha dang xay hoac nang cap
            && ! in_array($Junta, $herosLeave) // nha co HK dang roi khoi
            && $this->config['options']['b_'.$b['ID']] // option checked?
        ) {
          //addLog('Hỏi thăm HK ('. $b['Name'] .')');
          $this->hoitham($Junta);
        }
      }
      foreach ($herosLeave as $Junta) {
        $b = $this->getJuntaBuilding($Junta);
        if ($this->config['options']['b_'.$b['ID']]) {// chi xu li neu da chon nha
          //addLog('Xu li HK nha '. $this->template['Junta'][$Junta]);
          $this->thueHK($Junta);
        }
      }
    }

    if (self::$checkTime != $nextTime) {
      $this->config['needUpdate'] = $now + $nextTime;//force refresh info in the next update
    }

    addDebug($data);
    
    //$this->doihinh();
    
    if ($flag['repeat']) $this->processEvent();
    if ($flag['bophong']) $this->bophong();
    
    return $data;
  }
  
  function thuthap() {
    if (! $this->config['options']['thuthap_pos'][0]) {
      $Lands = $this->getLandsInfo($this->CityPos);
      $this->config['options']['thuthap_pos'] = array($Lands['Spaces'][0]);
      $this->saveConfig();
    }

    $result = ajax_AddSearchEvent($this->CityID, $this->config['options']['thuthap_pos'][0]);
    addDebug($result);

    $errorCode = Tools::decode($result->data);
    if ($errorCode === 0) {
      addLog('Search location ('. renderPos($this->config['options']['thuthap_pos']) .')');
    }
    else {
      addLog('Search error: '. $errorCode);
    }
  }
  
  function nhiemvu() {
    $result = ajax_GetOtherTaskSimple($this->CityID, 1);
    $group = Tools::decode($result->data);

    if ($group[0]->SubType != 0) {
      // kiem tra nv hien tai
      $result = ajax_GetOtherTaskByType($this->CityID, 1, $group[0]->SubType);
      $nv = Tools::decode($result->data);
      addLog('Nhiem vu co ten '.$group[0]->Name.' va subtype='.$group[0]->SubType.' va ID '.$nv[0]->ID);
      
      //if (in_array($group[0]->SubType, array(12, 13))) {
      if ($nv[0]->GetItem->Quality == 3 && $nv[0]->GetItem->Level >= 4) {
        return;
      }

      //ajax_DeleteTask($nv[0]->ID);
    }

    $result = ajax_AddDailyTaskEvent($this->CityID);
  }
  
  /*
    Xu li HK o nha trong luc dang tan cong
  */
  function xuliHK() {
    
    $update = false;
    $taingoai = false;  
    $threshold = $GLOBALS['params'][JXW_TECHNIC_ULT][$this->config['CityInfo']['TechnicLevel'][JXW_TECHNIC_ULT-1]];
    //addLog('Threshold = '.$threshold);
    
    foreach ($this->config['HeroInfo'] as $H) {
      if (in_array($H['State'], array(JXW_HERO_STATE_TAINGOAI, JXW_HERO_STATE_NGOAITHUONG, JXW_HERO_STATE_CHIVIEN))) {
        $taingoai = true;
        break;
      }
    }
    
    // chi xu li khi co HK dang tai ngoai
    if (! $taingoai) return;

    foreach ($this->config['HeroInfo'] as $H) {
      if ($H['State'] != JXW_HERO_STATE_DOILENH) continue;
        
      $nhom = $this->config['options']['group_'. $H['ID']];
      
      if ($nhom == 1 || $H['ListType'] == JXW_HERO_LIST_BOPHONG) {
        if ($H['PrenticeNum'] < $H['MaxPrenticeNum']) {
          $update = true;
          $this->hiepkhach($H, 'chieumo', 'max');
        }
        elseif ($H['Training'] + $threshold < 110) {
          $this->hiepkhach($H, 'huanluyen');
        }
      }
      elseif ($nhom == 2) {
        if ($H['PrenticeNum'] < 4) {
          $update = true;
          $this->hiepkhach($H, 'chieumo', 4);
        }
      }
    }
    
    if ($update) {
      $this->needUpdate['HeroInfo'] = true;
    }
  }

  /**
   * Tim doi hinh 5 nguoi dang san sang de ra tran
   */
  function doihinh_xuatchien() {
    
    $total = 0;
    
    foreach ($this->config['HeroInfo'] as &$H) {
      if ($H['State'] == JXW_HERO_STATE_DOILENH && $H['ListType'] == JXW_HERO_LIST_TANCONG) {
        $total++;
      }
    }
    
    $update = false;
    
    foreach ($this->config['HeroInfo'] as &$H) {
      if ($H['State'] != JXW_HERO_STATE_DOILENH && $H['ListType'] == JXW_HERO_LIST_TANCONG) {
        $this->hiepkhach($H, 'haubi');
        $update = true;
      }
      elseif ($H['State'] == JXW_HERO_STATE_DOILENH && $H['ListType'] != JXW_HERO_LIST_TANCONG && $H['PrenticeNum'] > 0) {
        if ($total < 5) {
          $this->hiepkhach($H, 'tancong');
          $update = true;
          $total++;
        }
      }
    }
    
    addLog('Da tim duoc doi hinh cuop boc gom '. $total .' HK');

    if ($update) {
      $this->needUpdate['HeroInfo'] = true;
    }
    
    return $total;
  }
  
  /* tu dong chon doi hinh thich hop de xuat chien
    - Chieu mo, huan luyen nhung HK can thiet
    - Neu du 5 HK, thi tiep tuc luyen level/skill
    - Neu khong du 5 HK level/skill, thi di cuop
      Dong thoi, cung chieu mo, huan luyen tat ca HK trong doi hinh 1, 2
  */ 
  function doihinh($NPC) {
    if (! $this->config['options']['op_switch']) {
      return $this->config['options']['xuattran'];
    }
    
    $threshold = $GLOBALS['params'][JXW_TECHNIC_ULT][$this->config['CityInfo']['TechnicLevel'][JXW_TECHNIC_ULT-1]];
    //addLog('chuyen doi hinh ne');
    
    // create a shortcut
    $gr = array();
    foreach ($this->config['HeroInfo'] as $H) {
      $gr[$H['ID']] =& $this->config['options']['group_'. $H['ID']];
    }
    addLog('Doi hinh '.$this->config['options']['xuattran']);
    
    // neu o che do cuop, thi k° lam gi ca
    if ($this->config['options']['xuattran'] == 'attack') {
      return $this->doihinh_xuatchien() > 0 ? 'attack' : '';
    }

    $action = '';

    // Truoc tien, kiem tra xem nhom 1 va 2 co du 5 nguoi ko
    $group = $this->config['options']['group'];//TODO: xac dinh $group theo $NPC
    if ($group == -1) $group = 5;
    $nhom = array(1 => $group, 2 => 5-$group);
    $hientai = array(1 => 0, 2 => 0);
    $toida = array(1 => 0, 2 => 0);

    $Heros = $this->config['HeroInfo'];
    $HK = array();
    foreach ($Heros as &$H) {
      $toida[$gr[$H['ID']]]++;

      if ($H['State'] != JXW_HERO_STATE_DOILENH) continue;

      if ($gr[$H['ID']] == 1) {
        if ($H['PrenticeNum']/$H['MaxPrenticeNum']*$H['Training'] >= 80 && $H['Training'] >= 90) {
          $hientai[1]++;
          $H['tag'] = 'xt';
          $HK[] = $H['Name'];
        }
        else $H['tag'] = 'hb';
      }
      elseif ($gr[$H['ID']] == 2) {
        if ($H['PrenticeNum'] >= 4) {
          $hientai[2]++;
          $H['tag'] = 'xt';
          $HK[] = $H['Name'];
        }
        else $H['tag'] = 'hb';
      }
      else $H['tag'] = 'hb';
    }
    
    // doi khi ko du 5 HK cho doi hinh
    $nhom[1] = min($nhom[1], $toida[1]);
    $nhom[2] = min($nhom[2], $toida[2]);
    
    addLog(sprintf('Doi hinh can co %d/%d. Hien tai co %d/%d (%s)', $nhom[1], $nhom[2], $hientai[1], $hientai[2], implode(',', $HK)));
    
    if ($hientai[1] >= $nhom[1] && $hientai[2] >= $nhom[2]) {
      addLog('Du doi hinh, tan cong thoi');
      // du roi, tim 5 nguoi xuat tran
      // dau tien, dem so nguoi dang tan cong, nhung ai ko xt thi cho xuong hau bi
      foreach ($Heros as &$H) {
        if ($H['State'] != JXW_HERO_STATE_DOILENH) continue;

        if ($H['tag'] == 'xt' && $H['ListType'] == JXW_HERO_LIST_TANCONG) {
          $nhom[$gr[$H['ID']]]--;
        }
        if ($H['tag'] == 'hb' && $H['ListType'] == JXW_HERO_LIST_TANCONG) {
          $this->hiepkhach($H, 'haubi');
        }
      }

      // tiep theo, neu thieu nguoi...
      foreach ($Heros as &$H) {
        if ($H['State'] != JXW_HERO_STATE_DOILENH) continue;
          
        if ($H['tag'] == 'xt' && $nhom[$gr[$H['ID']]] > 0) {
          // dang thieu nguoi, cho HK du yeu cau vao tan cong
          $nhom[$gr[$H['ID']]]--;
          $this->hiepkhach($H, 'tancong');
        }
        else {
          // neu khong trong nhom xt, thi chieu mo, huan luyen neu can thiet
          if ($gr[$H['ID']] == 1) {
            if ($H['PrenticeNum']/$H['MaxPrenticeNum']*$H['Training'] < 80 || $H['Training'] < 90) {
              if ($H['PrenticeNum'] < $H['MaxPrenticeNum']) {
                $this->hiepkhach($H, 'chieumo', 'max');
              }
              else {
                $this->hiepkhach($H, 'huanluyen');
              }
            }
          }
          elseif ($gr[$H['ID']] == 2) {
            if ($H['PrenticeNum'] < 4) {
              $this->hiepkhach($H, 'chieumo', 4);
            }
          }
        }
      }
      $action = $this->config['options']['xuattran'];
    }
    else {
      // khong du nguoi, tam thoi nghi ngoi, tat ca deu chieu mo, huan luyen
      addLog('Tam thoi nghi ngoi');
      
      foreach ($Heros as &$H) {
        if ($H['State'] != JXW_HERO_STATE_DOILENH) continue;

        //addLog('Xu li em '.$H['Name']);
        if ($gr[$H['ID']] == 1) {
          if ($H['PrenticeNum'] < $H['MaxPrenticeNum']) {
            $this->hiepkhach($H, 'chieumo', 'max');
          }
          elseif ($H['Training'] <= 90) {
            $this->hiepkhach($H, 'huanluyen');
          }
        }
        elseif ($gr[$H['ID']] == 2) {
          if ($H['PrenticeNum'] < 4) {
            $this->hiepkhach($H, 'chieumo', 4);
          }
        }
      }

      $action = 'attack';
      $action = '';//nghi ngoi
    }

    return $action;
  }

  function xuattran_attack($real = true) {
    //Cuop
    $Victims = $this->config['options']['attack_pos'];
    if (count($Victims) == 0) return;
    $oldest = time() - self::$loopTime;
    $vic = 0;
    foreach ($Victims as $p=>$v) {
      if ($v[1] < $oldest) $v[1] = $oldest + Tools::TravelTime($this, $v[0]);
      if ($v[1] < $Victims[$vic][1] || $vic == 0) $vic = $p;
    }
    
    if ($Victims[$vic][1] > time() - self::$attackTime) {
      // khong tan cong lien tiep (cung co the do loi)
      addLog('Khong co nan nhan.');
      return false;
    }
    
    $NPC = new stdClass();
    $NPC->ID = $Victims[$vic][0];
    $NPC->Pos = $vic;
    $NPC->Type = JXW_UNIT_CITY;
    $NPC->ActionType = JXW_ACTION_CONGKICH;

    if ($real) {
      $this->config['options']['attack_pos'][$vic][1] = time();
      $this->saveConfig();
      addLog('Tấn công toạ độ '. renderPos($NPC->Pos));
    }
    
    return $NPC;
  }
  
  function xuattran_level($real = false) {
    if (! $this->config['options']['level_pos'][0]) {
      $this->config['options']['level_pos'] = array($this->searchNPCByLevel($this->config['options']['level_lv']));
    }
    $NPC = $this->getNPCInfo($this->config['options']['level_pos'][0]);
    $NPC->ActionType = JXW_ACTION_CONGKICH;
    
    if ($real) {
      addLog('Tấn công ST '. renderPos($NPC->Pos));
    }
    
    return $NPC;
  }
  
  function xuattran_skill($real = false) {
    if (! $this->config['options']['skill_pos'][0]) {
      $this->config['options']['skill_pos'] = array($this->searchNPCByLevel($this->config['options']['skill_lv']));
    }
    $NPC = $this->getNPCInfo($this->config['options']['skill_pos'][0]);
    addLog(sprintf('ST lv %d tang %d/%d', $NPC->Level, $NPC->NpcFloor, $NPC->NpcFloorMax));

    if ($NPC->NpcFloor == 0 || $NPC->NpcFloorMax < $this->config['options']['attack_min'] || $NPC->NpcFloor > $this->config['options']['attack_max']) {
      $NPC->ActionType = JXW_ACTION_CONGKICH;
    }
    else {
      $NPC->ActionType = JXW_ACTION_DOTHAM;
    }
    
    return $NPC;
  }

  function xuattran($action = false) {
    
    $this->updateHeroInfo();

    if (! $action) $action = $this->config['options']['xuattran'];

    if ($action == 'attack') {
      $NPC = $this->xuattran_attack(true);
    }
    elseif ($action == 'level') {
      $NPC = $this->xuattran_level(false);
    }
    elseif ($action == 'skill') {
      $NPC = $this->xuattran_skill(false);
    }
    
    if (! $NPC) return;
    
    $kiemtra = $this->doihinh($NPC);

    if ($kiemtra != $action) {
      if (! empty($kiemtra)) $this->xuattran($kiemtra);
    }
    else {
      $speedFlag = array(0,0,0,0,0,0,0,0,0,0);
      //check quang duong, chon cach di chuyen 20 xu
      //...
      $NPC->Type = JXW_UNIT_CITY; //it's weird :-(
      $result = ajax_AddCorpsEventExtend($this->CityID, $NPC->Pos, $NPC->ID, $NPC->Type, $NPC->ActionType, $speedFlag);
      $code = Tools::decode($result->data);
      addLog($action .' '. renderPos($NPC->Pos). ': ' . $code);
    }
  }

  function bophong($enabled = true) {
    
    // khi da hen gio bo phong sau chien su, thi khong bo phong truoc do nua
    if ($this->config['Actions']['op']['bophong'] > time()) return;
    
    $this->config['Actions']['op']['bophong'] = PHP_INT_MAX;// available since 4.4 and 5.0.5
    
    if ($enabled) {//xay dung
      
      $result = ajax_GetMapUnitInfo($this->CityID, JXW_MAP_DEFENCE, 0);
      $units = Tools::decode($result->data);
      //addLog($result->data);
      
      $total = $this->config['options']['bp'];
      $HKbophong = 0;
      $map = array(140, 145, 150, 196); // 4 kho chua
      foreach ($units as $unit) {
        $map[] = $unit->Pos;
        if ($unit->Type == 2) {
          $total[$unit->Index]--;
        }
        elseif ($unit->Type == 1) {
          $HKbophong++;
        }
      }
  
      $Pos = 69;
      
      // bo phong HK
      $update = false;
      foreach ($this->config['HeroInfo'] as $H) {
        if ($H['ListType'] == JXW_HERO_LIST_HAUBI && $H['PrenticeNum'] > 0 && $HKbophong++ < 5) {
          while (in_array($Pos, $map)) {$Pos++;}
          $this->hiepkhach($H, 'bophong', $Pos);
          $map[] = $Pos;
          $update = true;
        }
      }
      if ($update) {
        $this->temp['UpdateHeroInfo'] = true;
      }
      
      // xay nhung cai con thieu, xay tat ca 1 lan luon!
      // TODO: kiem tra cac unit dang cho xay de giam cac request ko hop le
      $maxwait = 5;
      foreach ($total as $j => $n) {
        while ($n-- > 0 && $maxwait-- > 0) {//xay
          while (in_array($Pos, $map)) {$Pos++;}
          ajax_AddBuildingEvent($this->CityID, JXW_ACTION_XAY, JXW_OBJ_DEFENCE, $j, $Pos);
          addLog('Xay tai toa do '. $Pos);
          $map[] = $Pos;
        }
      }
    }
    else {
      addLog('huy bp');
      // huy bo phong HK
      $update = false;
      foreach ($this->config['HeroInfo'] as $H) {
        if ($H['ListType'] == JXW_HERO_LIST_BOPHONG) {
          $this->hiepkhach($H, 'haubi');
          $update = true;
        }
      }
      if ($update) {
        $this->needUpdate['HeroInfo'] = true;
      }
    }
  }

  function hoitham($Junta) {// $Junta = $Index-11
    if ($Junta < 1 || $Junta > 10 || !is_int($Junta)) return;
    // binh thuong tree_a_2_6_0_0
    // tim nhanh tree_a_2_56_0_0_1
    $b = $this->getJuntaBuilding($Junta);
    
    if ($this->config['options']['hoitham_quick']) {
      ajax_AddVisitEvent($this->CityID, JXW_ACTION_HERO_QUICKASK, JXW_OBJ_HERO, $Junta + 11, $b['Pos'], 1);
      //addLog('Hoi tham nhanh');
    }
    else {
      ajax_AddBuildingEvent($this->CityID, JXW_ACTION_HERO_ASK, JXW_OBJ_HERO, $Junta + 11, $b['Pos']);
    }
    // AddBuildingEvent(actionType,objType,objID,pos);//添加建筑事件
    //ajax_AddVisitEvent{"cityID":16851,"actionType":27,"objType":1,"objID":20,"pos":4,"goldFlag":1}
  }

  function thueHK($Junta) {
    $result = ajax_GetCanEenageHero($this->CityID, $Junta);
    $heros = Tools::decode($result->data);
    addDebug($heros);
    
    $opt = $this->config['options'];
    
    foreach ($heros as $hero) {// thuong thuong chi hoi tham duoc 1 hero thoi :P
      if ($hero->ID <= 0) continue;
      
      if ($hero->Quality >= $opt['ht_quality']
          && $hero->Dodge >= $opt['ht_dodge']
          && $hero->MaxPrenticeNum >= $opt['ht_prentice']
          && $hero->Attack >= $opt['ht_attack']
      ) {
        //Main.EngageHero(CityID,objID,cb_HeroCommandUpdate);//雇佣英雄
        $result = ajax_EngageHero($this->CityID, $hero->ID);
        addLog(Tools::decode($result->data));
        alert("Thuê được \n\n". var_export($hero, true));
      }
      else {
        //Main.FireCanEenageHero(CityID,objID,cb_HeroCommandUpdate);//遣散英雄    993941
        $result = ajax_FireCanEenageHero($this->CityID, $hero->ID);
        addLog(sprintf('HK %s, %d-%d-%d => fire!', $this->template['HeroQuality'][$hero->Quality-1], $hero->Attack, $hero->Dodge, $hero->MaxPrenticeNum));
      }
    }
    
    //Tiep tuc chieu mo
    if ($this->config['options']['op_hoitham']) {
      $b = $this->getJuntaBuilding($Junta);
      // option still checked?
      if ($this->config['options']['b_'.$b['ID']]) {
        //addLog('Tiep tuc tham HK nha <'. $b['Name'] .'>');
        $this->hoitham($Junta);
      }
    }
  }

  function autoplay() {
    if (! $this->config['options']['enabled']) return;
    $this->hooks['UpdateHeroInfo'] = array('xuliHK');
    $this->needUpdate = array('HeroInfo' => false, 'UserInfo' => false);

    $this->processEvent();

    if ($this->needUpdate['UserInfo']) {
      $this->updateUserInfo(true);
    }
    elseif ($this->needUpdate['HeroInfo']) {
      $this->updateHeroInfo();
    }

    $this->saveConfig();
  }
}